"""
数据库初始化脚本
"""
from app.core.database import engine, SessionLocal, Base
from app.models.user import User
from app.models.machine import Machine

# 导入其他模型
import bcrypt

def init_db():
    """初始化数据库表"""
    # 创建所有表
    Base.metadata.create_all(bind=engine)
    print("数据库表创建成功")
    
    # 初始化默认用户数据
    db = SessionLocal()
    try:
        # 检查是否已存在用户
        user_count = db.query(User).count()
        if user_count == 0:
            # 创建默认管理员用户
            admin_password = bcrypt.hashpw("admin123".encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
            admin_user = User(
                username="admin",
                password=admin_password,
                name="管理员",
                role="admin",
                email="admin@example.com",
                avatar="👤"
            )
            db.add(admin_user)
            
            # 创建默认普通用户
            user_password = bcrypt.hashpw("user123".encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
            normal_user = User(
                username="user",
                password=user_password,
                name="普通用户",
                role="user",
                email="user@example.com",
                avatar="👨‍💻"
            )
            db.add(normal_user)
            
            db.commit()
            print("默认用户数据初始化成功")
        else:
            print("用户数据已存在，跳过初始化")
    except Exception as e:
        print(f"初始化用户数据时出错: {e}")
        db.rollback()
    finally:
        db.close()

def drop_db():
    """删除所有表"""
    Base.metadata.drop_all(bind=engine)
    print("数据库表删除成功")

if __name__ == "__main__":
    init_db()